package com.talent.jiwen.home;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.HomeFragment;
import com.talent.jiwen.IndexActivity;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.InvitedListResult;
import com.talent.jiwen.http.result.SaveOrderResult;
import com.talent.jiwen.teacher.CourseFragment;
import com.talent.jiwen.teacher.CourseListFragment;
import com.talent.jiwen.ui.widgets.LoadDialog;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.talent.jiwen.util.downtime.DownTimer;
import com.talent.jiwen.util.downtime.DownTimerListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;

public class TogetherListActivity extends BaseActivity implements DownTimerListener {
    @BindView(R.id.min_1)
    TextView min_1;
    @BindView(R.id.min_2)
    TextView min_2;
    @BindView(R.id.sec_1)
    TextView sec_1;
    @BindView(R.id.sec_2)
    TextView sec_2;
    @BindView(R.id.timeTv)
    TextView timeTv;
    @BindView(R.id.numTv)
    TextView numTv;
    @BindView(R.id.topLayout)
    LinearLayout topLayout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.cancelTogetherTv)
    TextView cancelTogetherTv;
    @BindView(R.id.askLayout)
    RelativeLayout askLayout;

    private DownTimer downTimer;

    private static final String PARAM_ANSWER_TIME = "param.answer.time";
    private static final String PARAM_CREATE_TIME = "param.create.time";
    private static final String PARAM_GROUP_ID = "param.group.id";
    private static final String PARAM_ORDER_ID = "param.order.id";
    private String groupId;
    private String orderId;

    private int count = 0;//接受拼班的人数

    private List<InvitedListResult.Invited> dataList = new ArrayList<>();
    public static final String EVENT_REFRESH_INVITE_LIST = "event.refresh.invite.list";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_together_list;
    }

    @Override
    public String titleName() {
        return getString(R.string.together_study);
    }

    @Override
    protected void initData() {

        registEventBus();

        groupId = getIntent().getStringExtra(PARAM_GROUP_ID);
        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);
        String answerTime = getIntent().getStringExtra(PARAM_ANSWER_TIME);

        SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH点mm分");
        timeTv.setText(df.format(new Date(Long.parseLong(answerTime))));


        downTimer = new DownTimer();
        downTimer.setListener(this);

        long createTime = getIntent().getLongExtra(PARAM_CREATE_TIME , System.currentTimeMillis());
        long countTime = (15 * 60 * 1000) - (System.currentTimeMillis() - createTime);
        downTimer.startMinDown(countTime);

        mHeadRightText.setVisibility(View.VISIBLE);
        mHeadRightText.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.common_app_color));
        mHeadRightText.setText(getString(R.string.add_friend));
        mHeadRightText.setTextSize(TypedValue.COMPLEX_UNIT_SP , 15);
        mHeadRightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SearchFriendActivity.startSearchFriendActivity(TogetherListActivity.this , groupId);
            }
        });
        mBtnLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });


        LinearLayoutManager layoutManager = new LinearLayoutManager(TogetherListActivity.this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerView.setAdapter(new CommonAdapter<InvitedListResult.Invited>(TogetherListActivity.this , R.layout.item_together_list , dataList){
            @Override
            protected void convert(ViewHolder holder, final InvitedListResult.Invited invited, int position) {
                ImageView headIv = holder.getView(R.id.headIv);
                TextView nameTv = holder.getView(R.id.nameTv);
                TextView gradeTv = holder.getView(R.id.gradeTv);
                TextView optionTv = holder.getView(R.id.optionTv);

                ImageUtil.loadCircleImage(TogetherListActivity.this ,invited.getUserHeadImage() , headIv);
                nameTv.setText(invited.getStudentName());
//                if (invited.getGradeLeve() != 0){
//                    gradeTv.setVisibility(View.VISIBLE);
//                    gradeTv.setText(Constant.gradeMap.get(invited.getGradeLeve()));
//                }else{
//                    gradeTv.setVisibility(View.GONE);
//                }
                gradeTv.setVisibility(View.GONE);

                optionTv.setEnabled(false);
                switch (invited.getGroupStatus()){
                    case 0:
                    case 5:
                        optionTv.setText("邀请");
                        optionTv.setBackgroundResource(R.drawable.bg_circle_theme);
                        optionTv.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.white));
                        optionTv.setEnabled(true);
                        optionTv.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                inviteStudentJoinGroup(invited.getStudentId());
                            }
                        });
                        break;
                    case 1:
                        //已接收
                        optionTv.setText("已接受");
                        optionTv.setBackground(null);
                        optionTv.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.common_app_color));
                        break;
                    case 2:
                        //已拒绝
                        optionTv.setText("已拒绝");
                        optionTv.setBackground(null);
                        optionTv.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.red));
                        break;
                    case 3:
                        //已失效
                        optionTv.setText("已失效");
                        optionTv.setBackground(null);
                        optionTv.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.color_BDBDBD));
                        break;
                    case 4:
                        //已邀请
                        optionTv.setText("已邀请");
                        optionTv.setBackground(null);
                        optionTv.setTextColor(ContextCompat.getColor(TogetherListActivity.this , R.color.color_BDBDBD));
                        break;
                }

            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getInvitedStudentList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();
    }

    @Subscribe
    public void onEvent(String string){
        if (string.equals(EVENT_REFRESH_INVITE_LIST)){
            refreshLayout.autoRefresh();
        }
    }

    @OnClick({R.id.askLayout , R.id.cancelTogetherTv})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.askLayout:
                if (count < 5){
                    MaterialDialog.Builder dialog= MaterialDialogUtil.getCommonDialog(mContext, getString(R.string.title), getString(R.string.number_not_enough),
                            getString(R.string.agree), getString(R.string.cancel), new MaterialDialogUtil.OnDialogPoNeClickListener() {
                                @Override
                                public void onPositive() {
                                    publishOrderInfo();
                                }

                                @Override
                                public void onNegative() {

                                }
                            });

                    dialog.show();
                }else{
                    publishOrderInfo();
                }
                break;
            case R.id.cancelTogetherTv:
                cancelTogetherOrder();
                break;
        }


    }

    @Override
    public void onBackPressed() {
//        MaterialDialog.Builder dialog= MaterialDialogUtil.getCommonDialog(mContext, getString(R.string.title), getString(R.string.give_up_this_problem),
//                getString(R.string.agree), getString(R.string.cancel), new MaterialDialogUtil.OnDialogPoNeClickListener() {
//            @Override
//            public void onPositive() {
//                finish();
//            }
//
//            @Override
//            public void onNegative() {
//
//            }
//        });
//
//        dialog.show();
        EventBus.getDefault().post(HomeFragment.REFRESH_HOME_INFO);
        finish();
    }

    @Override
    public void onTick(long millisUntilFinished) {

    }

    @Override
    public void onFinish() {
        MaterialDialog.Builder dialog= MaterialDialogUtil.getCommonDialog(mContext, getString(R.string.title), getString(R.string.invite_time_out_content),
                getString(R.string.agree), getString(R.string.give_up_order), new MaterialDialogUtil.OnDialogPoNeClickListener() {
                    @Override
                    public void onPositive() {
                        publishOrderInfo();
                    }

                    @Override
                    public void onNegative() {
                        finish();
                    }
                });

        dialog.show();
    }

    @Override
    public void onMinTick(String str) {
        if(!Validators.isEmpty(str)&& str.length()==5){
            min_1.setText(String.valueOf(str.charAt(0)));
            min_2.setText(String.valueOf(str.charAt(1)));
            sec_1.setText(String.valueOf(str.charAt(3)));
            sec_2.setText(String.valueOf(str.charAt(4)));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
        if(downTimer!=null){
            downTimer.stopDown();
        }
    }

    /**获取邀请列表
     *
     */
    private void getInvitedStudentList(){
        Map<String, String> map = new HashMap<>();
        map.put("groupId" , groupId);
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getInvitedStudentList(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<InvitedListResult>(this) {
            @Override
            protected void _onNext(InvitedListResult invitedListResult) {
                dataList.clear();
                dataList.addAll(invitedListResult.getInvitedList());
                recyclerView.getAdapter().notifyDataSetChanged();

                refreshLayout.finishRefresh();

                count = 0 ;
                for (InvitedListResult.Invited invited : dataList){
                    if (invited.getGroupStatus() == 1){
                        count ++;
                    }
                }
                numTv.setText(count + "");

                if (count == 5){
                    MaterialDialog.Builder dialog= MaterialDialogUtil.getCommonDialog(mContext, getString(R.string.title), getString(R.string.number_six_enough),
                            getString(R.string.agree), getString(R.string.cancel), new MaterialDialogUtil.OnDialogPoNeClickListener() {
                                @Override
                                public void onPositive() {
                                    publishOrderInfo();
                                }

                                @Override
                                public void onNegative() {
                                    finish();
                                }
                            });

                    dialog.show();
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**邀请加入群组
     *
     */
    private void inviteStudentJoinGroup(String inviteStudentId){
        Map<String , String> map = new HashMap<>();
        map.put("groupId" , groupId);
        map.put("studentId" , inviteStudentId);
        map.put("inviteStudentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().inviteStudentJoinGroup(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                refreshLayout.autoRefresh();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }

    /**发布
     *
     */
    private void publishOrderInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("orderId" , orderId);
        map.put("studentId" , SPUtil.getUserId());

        Observable observable = ApiFactory.getEducationApiSingleton().publishOrderInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                IndexActivity.tab2checked = true;
                CourseFragment.fragment1Checked =true;
                EventBus.getDefault().post(CourseListFragment.REFRESH_COURSE_LIST);

                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }

    /**取消拼班
     *
     */
    private void cancelTogetherOrder(){
        Map<String, String> map = new HashMap<>();
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().cancelClassOrder(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(this) {
            @Override
            protected void _onNext(Void v) {
                EventBus.getDefault().post(HomeFragment.REFRESH_HOME_INFO);
                finish();
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }

    /**启动该页面
     *
     * @param context
     * @param groupId
     */
    public static void startTogetherActivity(Context context , String answerTime , long createTime , String groupId , String orderId){
        Intent intent = new Intent();
        intent.setClass(context , TogetherListActivity.class);
        intent.putExtra(PARAM_ANSWER_TIME , answerTime);
        intent.putExtra(PARAM_CREATE_TIME , createTime);
        intent.putExtra(PARAM_GROUP_ID , groupId);
        intent.putExtra(PARAM_ORDER_ID , orderId);
        context.startActivity(intent);
    }

}
